package sg4c.backend;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

public class BackendConnector {

    public final InputStream in;
    public final OutputStream out;
    public final InputStream err;
    public final Process subprocess;
    public final Thread dumpErrThread;

    public BackendConnector(String exepath) throws IOException {
        subprocess = Runtime.getRuntime().exec(exepath);
        in = subprocess.getInputStream();
        out = subprocess.getOutputStream();
        err = subprocess.getErrorStream();

        Runnable dumpErr = new Runnable() {

            public void run() {
                try {
                    byte[] buf = new byte[512];
                    int rct;
                    while ((rct = err.read(buf)) > 0) {
                        System.err.write(buf, 0, rct);
                    }
                } catch (IOException ex) {
                    ex.printStackTrace();
                    System.exit(1);
                }
            }
        };

        dumpErrThread = new Thread(dumpErr);
        dumpErrThread.start();
    }
}
